/*
 * Copyright (C) 2011-present ShenZhen iBOXCHAIN Information Technology Co.,Ltd.
 *
 * All right reserved.
 *
 * This software is the confidential and proprietary
 * information of iBOXCHAIN Company of China.
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with iBOXCHAIN inc.
 */
package com.example.wac.shiro.filter;

import cn.hutool.json.JSONUtil;
import com.example.wac.dto.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @author wuancheng
 * @description
 * @date 2023-04-14 18:22:00
 */

@Slf4j
public class RestAuthorizationFilter extends PermissionsAuthorizationFilter {
    public RestAuthorizationFilter() {
    }

    @Override
    protected boolean pathsMatch(String path, ServletRequest request) {
        String requestURI = this.getPathWithinApplication(request);
        String[] strings = path.split("@@");
        if (strings.length <= 1) {
            return this.pathsMatch(strings[0], requestURI);
        } else {
            String httpMethod = WebUtils.toHttp(request).getMethod();
            return httpMethod.equalsIgnoreCase(strings[1]) && this.pathsMatch(strings[0], requestURI);
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = this.getSubject(request, response);
        if (subject.getPrincipal() == null) {
            BaseResponse<Object> baseResponse = new BaseResponse<>(BaseResponse.RESULT_CODE_FAIL, "401", "用户未登录");
            flushMsgStrToClient(response, baseResponse);
        } else {
            String unauthorizedUrl = this.getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                BaseResponse<Object> baseResponse = new BaseResponse<>(BaseResponse.RESULT_CODE_FAIL, "403", "用户未授权");
                flushMsgStrToClient(response, baseResponse);
            } else {
                BaseResponse<Object> baseResponse = new BaseResponse<>(BaseResponse.RESULT_CODE_FAIL, "401", "用户未登录");
                flushMsgStrToClient(response, baseResponse);
            }
        }

        return false;
    }

    private static void flushMsgStrToClient(ServletResponse response, Object object) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(object));
        response.getWriter().flush();
    }
}
